<template>
  <div>
    <Nav :gwc_number="this.tableData.length"></Nav>
    <HeadNav></HeadNav>
    <el-card class="box-card card_gwc">
      <div slot="header" class="clearfix">
        <span>购物车</span>
        <el-button style="float: right; padding: 3px 0" type="text"
          >操作按钮</el-button
        >
      </div>
      <div class="text item">
        <el-table
        
          ref="multipleTable"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
          
          @selection-change="handleSelectionChange"
         empty-text="您还没有图书加入到购物车中，"
         
        >
          <el-table-column type="selection" width="40"> </el-table-column>
          <el-table-column label="全选" width="100"> </el-table-column>
          <el-table-column width="110" align="center">
            <template slot-scope="scope">
              <el-image
                style="height: 120px"
                :src=" scope.row.img"
              >
                <!-- <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div> -->
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="title" label="书名" width="180">
          </el-table-column>
          <el-table-column prop="author" label="作者" width="180">
          </el-table-column>
          <el-table-column label="单价" width="100">
            <template slot-scope="scope">
              <p>￥{{ scope.row.price }}</p>
            </template>
          </el-table-column>
          <el-table-column prop="num1" label="数量" width="250" align="center">
            <template slot-scope="scope">
              <el-input-number
                @change="handleChange"
                v-model="scope.row.count"
                :min="1"
                :max="20"
                label="hh"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="金额" width="170">
            <template slot-scope="scope">
              <p style="color: red">
                {{ (scope.row.price.replace("(台币)","").replace("USD","").replace("$","") * scope.row.count) | numFilter }}元
              </p>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <i
                @click="handleDelete(scope.$index, scope.row)"
                class="el-icon-delete"
                style="font-size: 25px;"
              ></i>
            </template>
          </el-table-column>
          <!-- <template slot-scope="scope">
              <i class="el-icon-delete" style="font-size: 25px;"></i>
            </template> -->
        </el-table>
        <div :class="this.tableData.length>4?'jiesuan_b':'jiesuan'">
          <ul>
            <li class="js_xz">
              <el-checkbox v-model="checked">全选</el-checkbox>
            </li>
            <li class="js_sc" @click="handleDelete_xz(tableChecked)">删除</li>
            <li class="js_num">
              已选商品<span style="color:#FF4400 ">{{ this.jiesuan.num }}</span
              >件
            </li>
            <li class="js_hj">
              合计（不含运费）：<span style="color:#FF4400 "
                >￥{{ this.jiesuan.price + 0.8 * this.jiesuan.num }}</span
              >
            </li>
            
            <li   class="js_js">
                <el-link @click.native="js" style="color:#fff" type="primary">结算</el-link></li>
          </ul>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import Nav from "../../com/components/Common/Nav.vue";
import HeadNav from "../../com/components/Common/HeadNav.vue";
import axios from "axios";
export default {
  components: { Nav, HeadNav },
  data() {
    return {
       loading: false,
      gwc_book: {},
      checked: false,
      list: [], //接口返回的购物车数组
      tableData: [], //经加工完成详细的图书详情购物车数组
      xz_list: [], //选中商品的数组
      jiesuan: {       //结算栏数据
        num: 0,
        price: 0,
      },
      
    };
  },
  methods: {

  js(){
     localStorage.setItem("order_list", JSON.stringify(this.xz_list));
     if(this.xz_list.length==0){
        this.$message({
          message: '您还没选中商品呢！',
          type: 'warning'
        });
     }else{
        this.$router.push({ path: '/dingdan', params: { userId: '123' }})
     }
     
     
     
  },
    handleChange() {                            //点击数量按钮渲染结算烂
   
       const token = localStorage.getItem("token");
      const userInfo = JSON.parse(localStorage.getItem("userInfo"));
      this.jiesuan.num = 0;
      this.jiesuan.price = 0;
      this.tableData.forEach((res) => {
         var params = new URLSearchParams();
        params.append('username', userInfo.username);
        params.append('count',res.count);
        params.append('bookId',res.bookId);
        axios                                                 //更改后端购物车图书数量请求
          .post("/fl-carts/addBookToCarts", params,{
            headers: {
            //  ' Access-control-expose-headers':'authorization',   
               'Content-Type': 'application/x-www-form-urlencoded',
              Authorization: token,        
            }        
          })
      });
      this.xz_list.forEach((element) => {
     

        this.jiesuan.num += element.count;

       
        var price = parseInt(element.price) * element.count;
    
        this.jiesuan.price += price;
      });
    },
    handleSelectionChange(val) {                            //点击选择框渲染结算栏
      
      this.loading=true;
     
     let list=[];
     for(let item of val){
       list.push(item.bookId);
     }
     this.xz_list=val;                      
      this.jiesuan.num = 0;
      this.jiesuan.price = 0;
      this.xz_list.forEach((element) => {
       
        this.jiesuan.num += element.count;
      
      
        var price = parseInt(element.price) * element.count;
      
        this.jiesuan.price += price;
      });
      if( this.tableData.length==0){
           this.checked = false;
      }
       else if(val.length == this.tableData.length) {
        this.checked = true;
      }else {
        this.checked = false;
      }
                  //先把购物车图书是否选中状态遍历修改为0
          var params = new URLSearchParams();
        params.append('username', this.userInfo.username);
        params.append('checkedType',0);
     
        axios                                  //更改后端数据库购物车商品勾选状态请求
          .post("/fl-carts/changeAllCheckedType", params,{
            headers: {
            // //  ' Access-control-expose-headers':'authorization',   
               
              Authorization: localStorage.getItem("token"),
         
            }     
          }).then(async(res)=>{
            
         
       
      
       //之前的小bug就是因为用了val遍历，导致val还没渲染完成就修改了后端商品勾选状态数据，所以这里先把val先赋值给this.xz_list,然后用这个数组再修改后端，完成debug
      
      var params1 = new URLSearchParams();
        params1.append('userId', this.userInfo.userId);
        params1.append('checkedType',1); //checkedTypeList
        params1.append('bookIds',list);
   axios
          .post("/fl-carts/batchChangeCheckedType",params1).then((res)=>{
            
            
            
            list=[]
          })
      
    
    })
this.loading=false;
      this.jiesuan.num = 0;
      this.jiesuan.price = 0;
      this.xz_list.forEach((element) => {
       
        this.jiesuan.num += element.count;
      
        var price = parseInt(element.price) * element.count;
       
        this.jiesuan.price += price;
      });
    },
    set_gwc() {                       //获取该用户请求的购物车数据，进行加工处理
      
      this.loading=true;
      const token = localStorage.getItem("token");
      this.userInfo = JSON.parse(localStorage.getItem("userInfo"));
      axios
        .get("/fl-carts/selectAllCartsByUsername", {
          params: {
            username: this.userInfo.username,
          },
          headers: {
            Authorization: token,
          },
        })
        .then(async (res) => {
           this.list = res.data.data;
         
          const that = this;
        
          for (let item of that.list) {
            await axios
              .get("/fl-book/searchBookByBookId", {
                params: {
                  bookId: item.bookId,
                },
                headers: {
                  Authorization: token,
                },
              })
              .then((res) => {
                this.$set(res.data.data,'count',item.count);  //添加count数量属性
                that.tableData.push(res.data.data);
              
               if(item.checked==1){
                 that.xz_list.push(res.data.data);
                 
               }
              
              })
              .catch((error) => {
                ;
              });
          }
    for(let item of this.xz_list) {
        
            this.$refs.multipleTable.toggleRowSelection(item,true);
    }
          this.loading=false;
        });
     
   
      
    },
    handleDelete(index, val) {        //删除单个图书
     
      

      this.$confirm("是否从购物车中移除该商品?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          axios
            .delete("/fl-carts/deleteOne", {
              params: {
                username: this.userInfo.username,
                bookId: val.bookId,
              },
              headers: {
                Authorization: localStorage.getItem("token"),
              },
            })
            .then((res) => {
            
              this.tableData.splice(index, 1);

            });

          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleDelete_xz() {             //批量删除选中的购物车中的图书
      const arr = [];
      this.xz_list.forEach((element) => {
        arr.push(element.bookId);
      });

      this.$confirm("是否从购物车中移除当前选中的商品?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var params = new URLSearchParams();
         
          params.append("username", this.userInfo.username);

          params.append("bookIds", arr);
          axios
            .delete("/fl-carts/deleteBatch", {
              params,
              headers: {
                Authorization: localStorage.getItem("token"),
              },
            })
            .then((res) => {
           
             
                                              
              this.xz_list.forEach((i) => {                      //批量删除后重新筛选数组渲染页面
              
                this.tableData.splice(
                  this.tableData.findIndex((j) => j.bookId === i.bookId),
                  1
                );
              });
           this.$message({
            type: "success",
            message: res.data.msg ,
          });
            });

          
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消退出",
          });
        });
    },
  },

  watch: {
    checked() {
   
        if (this.checked == true) {
        this.tableData.forEach((row) => {

          this.$refs.multipleTable.toggleRowSelection(row, true);
        });
      } 
     else if(this.xz_list.length == this.tableData.length-1){     //此处做判断是因为如果不做判断当全选然后再取消一个选项会导致其他选项也清空了，因此此次做一个判断

      }

      else{
        
         
              this.xz_list.forEach((row) => {
         
          this.$refs.multipleTable.toggleRowSelection(row, false);
        
        });
           
       
      
      }
     
    },
  },

  filters: {
    numFilter(value) {
      let realVal = "";
      if (!isNaN(value) && value !== "") {
        // 截取当前数据到小数点后两位
        realVal = parseFloat(value).toFixed(2);
      } else {
        realVal = "--";
      }
      return realVal;
    },
  },

  created() {
    this.set_gwc();
  
   
  },
};
</script>

<style>
.card_gwc {
  margin-left: 15.5%;
  width: 70%;
}
.jiesuan {
  width: 70%;
  height: 60px;
  background: #dedede;
  position: fixed;
  left: 15.5%;
  /* bottom: 0; */
  opacity: 1;
  z-index: 99999;
  float: left;
  margin-bottom: 10px;
}
.jiesuan_b {
  width: 70%;
  height: 60px;
  background: #dedede;
  position: fixed;
  left: 15.5%;
  bottom: 0;
  opacity: 1;
  z-index: 99999;
  

}
.jiesuan_b ul, .jiesuan ul {
 display: flex;

  line-height: 60px;
  text-align: center;
}
.jiesuan_b .js_xz{
     flex: 0.5;
}

.jiesuan ul .js_xz {
  flex: 0.5;
}

.jiesuan_b .js_sc{
   flex: 0.5;
}

.jiesuan .js_sc {
  flex: 0.5;
}
.jiesuan_b .js_num {
  flex: 3;
}

.jiesuan .js_num {
  flex: 3;
}
.jiesuan_b .js_hj{
    flex: 2;
}

.jiesuan .js_hj {
  flex: 2;
}
.jiesuan .js_num span {
  color: #ff4400;
  font-size: 20px;
  padding: 5px;
}
.jiesuan_b .js_num span {
  color: #ff4400;
  font-size: 20px;
  padding: 5px;
}
.jiesuan .js_hj span {
  font-size: 20px;
}
.jiesuan .js_js {
  flex: 1;
  width: 80px;
  height: 60px;
  background: #ff4400;
  font-size: 20px;
  color: #fff;
}
.jiesuan_b .js_js {
  flex: 1;
  width: 80px;
  height: 60px;
  background: #ff4400;
  font-size: 20px;
  color: #fff;
}


</style>
